package com.luckyframe.project.jmeter.report.controller;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Joiner;
import com.luckyframe.framework.web.controller.BaseController;
import com.luckyframe.project.jmeter.jmeterTestPlanRecord.domain.JmeterTestPlanRecord;
import com.luckyframe.project.jmeter.jmeterTestPlanRecord.service.IJmeterTestPlanRecordService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.jmeter.report.core.DataContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * druid 监控
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/jmeter/report/view")
public class JmeterReportViewController extends BaseController
{

    private final String geneReportPathPrefix="/jmeter_report_gened" ;

    @Autowired
    private IJmeterTestPlanRecordService planRecordService;


    @GetMapping("/viewbyId")
    public String index(@Param("planId")Long planId,@Param("recordId")Long recordId,@Param("caseId")Long caseId)
    {
        return redirect(
                Joiner.on(File.separator).join(geneReportPathPrefix,planId,recordId,caseId,"index.html"));
    }


    @GetMapping("/jmeter_report/**")
    public String test(HttpServletRequest httpServletRequest, ModelMap mm)
    {

        String requestURI = httpServletRequest.getRequestURI();

        String recordId = httpServletRequest.getParameter("recordId");
        if(StringUtils.isEmpty(recordId)|| !NumberUtil.isInteger(recordId)){
            throw new RuntimeException("参数错误 recordId非法 url=【"+requestURI+"】");
        }

        JmeterTestPlanRecord planRecord = planRecordService.selectJmeterTestPlanRecordById(Long.valueOf(recordId));

        String resultData = planRecord.getResultData();
        if(StringUtils.isNotEmpty(resultData)){
            DataContext dataContext = JSON.parseObject(resultData, DataContext.class);
            mm.putAll(dataContext);
        }

        mm.put("recordId",recordId);

        String path = requestURI.replace("/jmeter/report/view", "");

        return path;
    }

}
